package org.dromara.system.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.dromara.common.core.constant.CacheNames;
import org.dromara.common.core.constant.RoleConstants;
import org.dromara.common.core.constant.UserConstants;
import org.dromara.common.core.exception.ServiceException;
import org.dromara.common.core.utils.MapstructUtils;
import org.dromara.common.core.utils.PageUtils;
import org.dromara.common.core.utils.StreamUtils;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.common.mybatis.core.page.PageQuery;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.dromara.common.mybatis.helper.DataBaseHelper;
import org.dromara.common.satoken.utils.LoginHelper;
import org.dromara.system.domain.*;
import org.dromara.system.domain.bo.SysStoreBo;
import org.dromara.system.domain.bo.SysUserBo;
import org.dromara.system.domain.vo.*;
import org.dromara.system.mapper.*;
import org.dromara.system.service.ISysUserService;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 用户 业务层处理
 *
 * @author Lion Li
 */
@Slf4j
@RequiredArgsConstructor
@Service
public class SysUserServiceImpl implements ISysUserService {

    private final SysUserMapper baseMapper;
    private final SysDeptMapper deptMapper;
    private final SysRoleMapper roleMapper;
    private final SysPostMapper postMapper;
    private final SysUserRoleMapper userRoleMapper;
    private final SysUserDeptMapper userDeptMapper;
    private final SysUserDeviceMapper userDeviceMapper;
    private final SysUserStoreMapper userStoreMapper;

    private final SysUserAreaMapper userAreaMapper;




    @Override
    public TableDataInfo<SysUserVo> selectPageUserList(SysUserBo user, PageQuery pageQuery) {
        List<SysUserVo> pagedRecords = baseMapper.selectPageUserList(user);
        TableDataInfo<SysUserVo> tableDataInfo = new TableDataInfo<>();
        int total = pagedRecords.size();
        if (CollectionUtils.isEmpty(pagedRecords)){
            tableDataInfo.setTotal(total);
            tableDataInfo.setRows(pagedRecords);
            return tableDataInfo;
        }
        List<Long> userIds = pagedRecords.stream().map(SysUserVo::getUserId).collect(Collectors.toList());
        List<SysRoleVo> sysRoleVos = baseMapper.selectUserRoleListByUser(userIds);
        Map<Long, List<SysRoleVo>> userRoleMap = sysRoleVos.stream()
                .collect(Collectors.groupingBy(SysRoleVo::getUserId));
        List<SysDeptVo> sysDeptVos = baseMapper.selectUserDeptListByUser(userIds);
        Map<Long, List<SysDeptVo>> userDeptMap = sysDeptVos.stream()
                .collect(Collectors.groupingBy(SysDeptVo::getUserId));
        for (SysUserVo sysUserVo : pagedRecords) {
            sysUserVo.setDepts(userDeptMap.get(sysUserVo.getUserId()));
            sysUserVo.setRoles(userRoleMap.get(sysUserVo.getUserId()));
        }

        if (ObjectUtil.isNotNull(pageQuery.getPageSize()) || ObjectUtil.isNotNull(pageQuery.getPageNum())){
            pagedRecords = PageUtils.getPageData(pagedRecords, pageQuery.getPageNum() - 1, pageQuery.getPageSize());
        }
        tableDataInfo.setTotal(total);
        tableDataInfo.setRows(pagedRecords);
        return tableDataInfo;
    }


    /**
     * 根据条件分页查询用户列表
     *
     * @param user 用户信息
     * @return 用户信息集合信息
     */
    @Override
    public List<SysUserVo> selectUserList(SysUserBo user) {
        return baseMapper.selectUserList(this.buildQueryWrapper(user));
    }

    private Wrapper<SysUser> buildQueryWrapper(SysUserBo user) {
        Map<String, Object> params = user.getParams();
        QueryWrapper<SysUser> wrapper = Wrappers.query();
        wrapper.eq("u.del_flag", UserConstants.USER_NORMAL)
                .eq(ObjectUtil.isNotNull(user.getUserId()), "u.user_id", user.getUserId())
                .like(StringUtils.isNotBlank(user.getUserName()), "u.user_name", user.getUserName()).
                like(StringUtils.isNotBlank(user.getNickName()), "u.nick_name", user.getNickName())
                .eq(StringUtils.isNotBlank(user.getStatus()), "u.status", user.getStatus())
                .like(StringUtils.isNotBlank(user.getPhonenumber()), "u.phonenumber", user.getPhonenumber())
                .between(params.get("beginTime") != null && params.get("endTime") != null,
                        "u.create_time", params.get("beginTime"), params.get("endTime"))
                .and(ObjectUtil.isNotNull(user.getDeptId()), w -> {
                    List<SysDept> deptList = deptMapper.selectList(new LambdaQueryWrapper<SysDept>()
                            .select(SysDept::getDeptId)
                            .apply(DataBaseHelper.findInSet(user.getDeptId(), "ancestors")));
                    List<Long> ids = StreamUtils.toList(deptList, SysDept::getDeptId);
                    ids.add(user.getDeptId());
                    w.in("u.dept_id", ids);
                }).orderByAsc("u.user_id");
        return wrapper;
    }

    /**
     * 根据条件分页查询已分配用户角色列表
     *
     * @param user 用户信息
     * @return 用户信息集合信息
     */
    @Override
    public TableDataInfo<SysUserVo> selectAllocatedList(SysUserBo user, PageQuery pageQuery) {
        QueryWrapper<SysUser> wrapper = Wrappers.query();
        wrapper.eq("u.del_flag", UserConstants.USER_NORMAL)
            .eq(ObjectUtil.isNotNull(user.getRoleId()), "r.role_id", user.getRoleId())
            .like(StringUtils.isNotBlank(user.getUserName()), "u.user_name", user.getUserName())
            .eq(StringUtils.isNotBlank(user.getStatus()), "u.status", user.getStatus())
            .like(StringUtils.isNotBlank(user.getPhonenumber()), "u.phonenumber", user.getPhonenumber())
            .orderByAsc("u.user_id");
        Page<SysUserVo> page = baseMapper.selectAllocatedList(pageQuery.build(), wrapper);
        return TableDataInfo.build(page);
    }

    /**
     * 根据条件分页查询未分配用户角色列表
     *
     * @param user 用户信息
     * @return 用户信息集合信息
     */
    @Override
    public TableDataInfo<SysUserVo> selectUnallocatedList(SysUserBo user, PageQuery pageQuery) {
        List<Long> userIds = userRoleMapper.selectUserIdsByRoleId(user.getRoleId());
        QueryWrapper<SysUser> wrapper = Wrappers.query();
        wrapper.eq("u.del_flag", UserConstants.USER_NORMAL)
            .and(w -> w.ne("r.role_id", user.getRoleId()).or().isNull("r.role_id"))
            .notIn(CollUtil.isNotEmpty(userIds), "u.user_id", userIds)
            .like(StringUtils.isNotBlank(user.getUserName()), "u.user_name", user.getUserName())
            .like(StringUtils.isNotBlank(user.getPhonenumber()), "u.phonenumber", user.getPhonenumber())
            .orderByAsc("u.user_id");
        Page<SysUserVo> page = baseMapper.selectUnallocatedList(pageQuery.build(), wrapper);
        return TableDataInfo.build(page);
    }

    /**
     * 通过用户名查询用户
     *
     * @param userName 用户名
     * @return 用户对象信息
     */
    @Override
    public SysUserVo selectUserByUserName(String userName) {
        return baseMapper.selectUserByUserName(userName);
    }

    /**
     * 通过手机号查询用户
     *
     * @param phonenumber 手机号
     * @return 用户对象信息
     */
    @Override
    public SysUserVo selectUserByPhonenumber(String phonenumber) {
        return baseMapper.selectUserByPhonenumber(phonenumber);
    }

    /**
     * 通过用户ID查询用户
     *
     * @param userId 用户ID
     * @return 用户对象信息
     */
    @Override
    public SysUserVo selectUserById(Long userId) {
        return baseMapper.selectUserById(userId);
    }

    /**
     * 查询用户所属角色组
     *
     * @param userName 用户名
     * @return 结果
     */
    @Override
    public String selectUserRoleGroup(String userName) {
        List<SysRoleVo> list = roleMapper.selectRolesByUserName(userName);
        if (CollUtil.isEmpty(list)) {
            return StringUtils.EMPTY;
        }
        return StreamUtils.join(list, SysRoleVo::getRoleName);
    }

    /**
     * 查询用户所属岗位组
     *
     * @param userName 用户名
     * @return 结果
     */
    @Override
    @Deprecated
    public String selectUserPostGroup(String userName) {
        List<SysPostVo> list = postMapper.selectPostsByUserName(userName);
        if (CollUtil.isEmpty(list)) {
            return StringUtils.EMPTY;
        }
        return StreamUtils.join(list, SysPostVo::getPostName);
    }

    /**
     * 校验用户名称是否唯一
     *
     * @param user 用户信息
     * @return 结果
     */
    @Override
    public boolean checkUserNameUnique(SysUserBo user) {
        boolean exist = baseMapper.exists(new LambdaQueryWrapper<SysUser>()
            .eq(SysUser::getUserName, user.getUserName())
            .ne(ObjectUtil.isNotNull(user.getUserId()), SysUser::getUserId, user.getUserId()));
        return !exist;
    }

    /**
     * 校验手机号码是否唯一
     *
     * @param user 用户信息
     */
    @Override
    public boolean checkPhoneUnique(SysUserBo user) {
        boolean exist = baseMapper.exists(new LambdaQueryWrapper<SysUser>()
            .eq(SysUser::getPhonenumber, user.getPhonenumber())
            .ne(ObjectUtil.isNotNull(user.getUserId()), SysUser::getUserId, user.getUserId()));
        return !exist;
    }

    /**
     * 校验email是否唯一
     *
     * @param user 用户信息
     */
    @Override
    public boolean checkEmailUnique(SysUserBo user) {
        boolean exist = baseMapper.exists(new LambdaQueryWrapper<SysUser>()
            .eq(SysUser::getEmail, user.getEmail())
            .ne(ObjectUtil.isNotNull(user.getUserId()), SysUser::getUserId, user.getUserId()));
        return !exist;
    }

    /**
     * 校验用户是否允许操作
     *
     * @param userId 用户ID
     */
    @Override
    public void checkUserAllowed(Long userId) {
        if (ObjectUtil.isNotNull(userId) && LoginHelper.isSuperAdmin(userId)) {
            throw new ServiceException("不允许操作超级管理员用户");
        }
    }

    /**
     * 校验用户是否有数据权限
     *
     * @param userId 用户id
     */
    @Override
    public void checkUserDataScope(Long userId) {
        if (ObjectUtil.isNull(userId)) {
            return;
        }
        if (LoginHelper.isSuperAdmin()) {
            return;
        }
        if (ObjectUtil.isNull(baseMapper.selectUserById(userId))) {
            throw new ServiceException("没有权限访问用户数据！");
        }
    }

    /**
     * 新增保存用户信息
     *
     * @param user 用户信息
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int insertUser(SysUserBo user) {
        SysUser sysUser = MapstructUtils.convert(user, SysUser.class);
        // 新增用户信息
        int rows = baseMapper.insert(sysUser);
        user.setUserId(sysUser.getUserId());
        // 新增用户与岗位管理
        insertUserRole(user, false);
        // 新增用户与部门管理
        insertUserDept(user, false);
        //新增区域
        insertUserArea(user);
        //新增门店
        insertUserStore(user);
        //新增设备
        insertUserDevice(user);
        return rows;
    }

    /**
     * 添加设备
     * @param user
     */
    private void insertUserDevice(SysUserBo user) {
        Long[] deviceIds = user.getDeviceIds();
        if (deviceIds == null){
            return;
        }
        List<Long> devices = Arrays.asList(deviceIds);
        if (ArrayUtil.isNotEmpty(devices)) {
            userDeviceMapper.delete(new LambdaQueryWrapper<SysUserDevice>().
                    eq(SysUserDevice::getUserId, user.getUserId()));
            List<SysUserDevice> sysUserDevices = devices.stream()
                    .map(device -> {
                        SysUserDevice sysUserDevice = new SysUserDevice();
                        sysUserDevice.setUserId(user.getUserId());
                        sysUserDevice.setDeviceId(device);
                        return sysUserDevice;
                    })
                    .collect(Collectors.toCollection(ArrayList::new));
            //批量插入关联设备
            userDeviceMapper.insertBatch(sysUserDevices);
        }
    }

    /**
     * 添加门店
     * @param user
     */
    private void insertUserStore(SysUserBo user) {
        Long[] storeIds = user.getStoreIds();
        if (storeIds == null) {
            return;
        }
        List<Long> stores = Arrays.asList(storeIds);
        if (ArrayUtil.isNotEmpty(stores)) {
            userStoreMapper.delete(new LambdaQueryWrapper<SysUserStore>().eq(SysUserStore::getUserId, user.getUserId()));
            List<SysUserStore> sysUserStores = stores.stream().map(store -> {
                SysUserStore sysUserStore = new SysUserStore();
                sysUserStore.setUserId(user.getUserId());
                sysUserStore.setStoreId(store);
                return sysUserStore;
            }).collect(Collectors.toCollection(ArrayList::new));
            //批量插入关联门店
            userStoreMapper.insertBatch(sysUserStores);
        }

    }

    /**
     * 添加区域
     * @param user
     */
    private void insertUserArea(SysUserBo user) {
        Long[] areaIds = user.getAreaIds();
        if (areaIds == null) {
            return;
        }
        List<Long> areas = Arrays.asList(areaIds);
        if (ArrayUtil.isNotEmpty(areas)){
            userAreaMapper.delete(new LambdaQueryWrapper<SysUserArea>().eq(SysUserArea::getUserId, user.getUserId()));
            List<SysUserArea> sysUserAreas = areas.stream().map(area -> {
                SysUserArea sysUserArea = new SysUserArea();
                sysUserArea.setUserId(user.getUserId());
                sysUserArea.setAreaId(area);
                return sysUserArea;
            }).collect(Collectors.toCollection(ArrayList::new));
            //批量插入关联门店
            userAreaMapper.insertBatch(sysUserAreas);
        }

    }

    /**
     * 注册用户信息
     *
     * @param user 用户信息
     * @return 结果
     */
    @Override
    public boolean registerUser(SysUserBo user, String tenantId) {
        user.setCreateBy(user.getUserId());
        user.setUpdateBy(user.getUserId());
        SysUser sysUser = MapstructUtils.convert(user, SysUser.class);
        sysUser.setTenantId(tenantId);
        return baseMapper.insert(sysUser) > 0;
    }

    /**
     * 修改保存用户信息
     *
     * @param user 用户信息
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int updateUser(SysUserBo user) {
        // 新增用户与角色管理
        insertUserRole(user, true);
        insertUserDept(user, true);
        //新增区域
        insertUserArea(user);
        //新增门店
        insertUserStore(user);
        //新增设备
        insertUserDevice(user);
        SysUser sysUser = MapstructUtils.convert(user, SysUser.class);
        // 防止错误更新后导致的数据误删除
        int flag = baseMapper.updateById(sysUser);
        if (flag < 1) {
            throw new ServiceException("修改用户" + user.getUserName() + "信息失败");
        }
        return flag;
    }

    /**
     * 用户授权角色
     *
     * @param userId  用户ID
     * @param roleIds 角色组
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void insertUserAuth(Long userId, Long[] roleIds) {
        insertUserRole(userId, roleIds, true);
    }

    /**
     * 修改用户状态
     *
     * @param userId 用户ID
     * @param status 帐号状态
     * @return 结果
     */
    @Override
    public int updateUserStatus(Long userId, String status) {
        return baseMapper.update(null,
            new LambdaUpdateWrapper<SysUser>()
                .set(SysUser::getStatus, status)
                .eq(SysUser::getUserId, userId));
    }

    /**
     * 修改用户基本信息
     *
     * @param user 用户信息
     * @return 结果
     */
    @Override
    public int updateUserProfile(SysUserBo user) {
        return baseMapper.update(null,
            new LambdaUpdateWrapper<SysUser>()
                .set(ObjectUtil.isNotNull(user.getNickName()), SysUser::getNickName, user.getNickName())
                .set(SysUser::getPhonenumber, user.getPhonenumber())
                .set(SysUser::getEmail, user.getEmail())
                .set(SysUser::getSex, user.getSex())
                .eq(SysUser::getUserId, user.getUserId()));
    }

    /**
     * 修改用户头像
     *
     * @param userId 用户ID
     * @param avatar 头像地址
     * @return 结果
     */
    @Override
    public boolean updateUserAvatar(Long userId, Long avatar) {
        return baseMapper.update(null,
            new LambdaUpdateWrapper<SysUser>()
                .set(SysUser::getAvatar, avatar)
                .eq(SysUser::getUserId, userId)) > 0;
    }

    /**
     * 重置用户密码
     *
     * @param userId   用户ID
     * @param password 密码
     * @return 结果
     */
    @Override
    public int resetUserPwd(Long userId, String password) {
        return baseMapper.update(null,
            new LambdaUpdateWrapper<SysUser>()
                .set(SysUser::getPassword, password)
                .eq(SysUser::getUserId, userId));
    }

    /**
     * 新增用户岗位信息
     *
     * @param user  用户对象
     * @param clear 清除已存在的关联数据
     */
    private void insertUserRole(SysUserBo user, boolean clear) {
        this.insertUserRole(user.getUserId(), user.getRoleIds(), clear);
    }

    /**
     * 新增用户岗位信息
     *
     * @param userId  用户ID
     * @param roleIds 岗位组
     * @param clear   清除已存在的关联数据
     */
    private void insertUserRole(Long userId, Long[] roleIds, boolean clear) {
        if (ArrayUtil.isNotEmpty(roleIds)) {
            // 判断是否具有此岗位的操作权限
            List<SysRoleVo> roles = roleMapper.selectRoleList(new LambdaQueryWrapper<>());
            if (CollUtil.isEmpty(roles)) {
                throw new ServiceException("没有权限访问岗位的数据");
            }
            List<Long> roleList = StreamUtils.toList(roles, SysRoleVo::getRoleId);
            if (!LoginHelper.isSuperAdmin(userId)) {
                roleList.remove(UserConstants.SUPER_ADMIN_ID);
            }
            List<Long> canDoRoleList = StreamUtils.filter(Arrays.asList(roleIds), roleList::contains);
            if (CollUtil.isEmpty(canDoRoleList)) {
                throw new ServiceException("没有权限访问岗位的数据");
            }
            if (clear) {
                // 删除用户与角色关联
                userRoleMapper.delete(new LambdaQueryWrapper<SysUserRole>().eq(SysUserRole::getUserId, userId));
            }
            // 新增用户与角色管理
            List<SysUserRole> list = StreamUtils.toList(canDoRoleList, roleId -> {
                SysUserRole ur = new SysUserRole();
                ur.setUserId(userId);
                ur.setRoleId(roleId);
                return ur;
            });
            userRoleMapper.insertBatch(list);
        }
    }


    /**
     * 新增用户部门信息
     * @param user  用户对象
     * @param clear 清除已存在的关联数据
     */
    private void insertUserDept(SysUserBo user, boolean clear) {
        Long[] depts = user.getDeptIds();
        if (ArrayUtil.isNotEmpty(depts)) {
            if (clear) {
                // 删除用户与部门关联
                userDeptMapper.delete(new LambdaQueryWrapper<SysUserDept>().eq(SysUserDept::getUserId, user.getUserId()));
            }
            // 新增用户与部门关联
            List<SysUserDept> list = StreamUtils.toList(Arrays.asList(depts), deptId -> {
                SysUserDept up = new SysUserDept();
                up.setUserId(user.getUserId());
                up.setDeptId(deptId);
                return up;
            });
            userDeptMapper.insertBatch(list);
        }
    }

    /**
     * 通过用户ID删除用户
     *
     * @param userId 用户ID
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int deleteUserById(Long userId) {
        // 删除用户与岗位表
        userRoleMapper.delete(new LambdaQueryWrapper<SysUserRole>().eq(SysUserRole::getUserId, userId));
        // 删除用户与部门表
        userDeptMapper.delete(new LambdaQueryWrapper<SysUserDept>().eq(SysUserDept::getUserId, userId));
        // 防止更新失败导致的数据删除
        int flag = baseMapper.deleteById(userId);
        if (flag < 1) {
            throw new ServiceException("删除用户失败!");
        }
        return flag;
    }

    /**
     * 批量删除用户信息
     *
     * @param userIds 需要删除的用户ID
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int deleteUserByIds(Long[] userIds) {
        for (Long userId : userIds) {
            checkUserAllowed(userId);
            checkUserDataScope(userId);
            //判断当前用户是否属于公司的超级管理员用户 admin
            checkUserRole(userId);
        }
        List<Long> ids = Arrays.asList(userIds);
        // 删除用户与岗位表
        userRoleMapper.delete(new LambdaQueryWrapper<SysUserRole>().in(SysUserRole::getUserId, ids));
        // 删除用户与部门表
        userDeptMapper.delete(new LambdaQueryWrapper<SysUserDept>().in(SysUserDept::getUserId, ids));
        // 防止更新失败导致的数据删除
        int flag = baseMapper.deleteBatchIds(ids);
        if (flag < 1) {
            throw new ServiceException("删除用户失败!");
        }
        return flag;
    }

    private void checkUserRole(Long userId) {
        if (ObjectUtil.isNull(userId)) {
            return;
        }
        if (LoginHelper.isSuperAdmin()) {
            return;
        }
        QueryWrapper<SysRole> wrapper = Wrappers.query();
        wrapper.eq("r.type", RoleConstants.ROLE_TYPE_SYSTEM)
                .eq("u.user_id",userId);
        List<SysRoleVo> sysRoleVos = roleMapper.selectRoleList(wrapper);
        if (!sysRoleVos.isEmpty()) {
            throw new ServiceException("不能删除管理员账号！");
        }
    }

    /**
     * 通过部门id查询当前部门所有用户
     *
     * @param deptId
     * @return
     */
    @Override
    public List<SysUserVo> selectUserListByDept(Long deptId) {
        LambdaQueryWrapper<SysUser> lqw = Wrappers.lambdaQuery();
        lqw.eq(SysUser::getDeptId, deptId);
        lqw.orderByAsc(SysUser::getUserId);
        return baseMapper.selectVoList(lqw);
    }

    @Override
    public List<SysUser> selectNickNameByIds(List<Long> userIds) {
        List<SysUser> sysUsers = baseMapper.selectList(new LambdaQueryWrapper<SysUser>()
                .select(SysUser::getNickName, SysUser::getUserId).in(SysUser::getUserId, userIds));
        return CollUtil.isEmpty(sysUsers) ? null :sysUsers;
    }

    /**
     * 通过用户id查询用户门店
     * @param userId
     * @return
     */
    @Override
    public List<Long> selectUserStoreListByUser(Long userId) {
        return baseMapper.selectUserStoreIdListByUser(userId);
    }


    @Cacheable(cacheNames = CacheNames.SYS_USER_NAME, key = "#userId")
    @Override
    public String selectUserNameById(Long userId) {
        SysUser sysUser = baseMapper.selectOne(new LambdaQueryWrapper<SysUser>()
            .select(SysUser::getUserName).eq(SysUser::getUserId, userId));
        return ObjectUtil.isNull(sysUser) ? null : sysUser.getUserName();
    }

    @Override
    @Cacheable(cacheNames = CacheNames.SYS_NICKNAME, key = "#userId")
    public String selectNicknameById(Long userId) {
        SysUser sysUser = baseMapper.selectOne(new LambdaQueryWrapper<SysUser>()
            .select(SysUser::getNickName).eq(SysUser::getUserId, userId));
        return ObjectUtil.isNull(sysUser) ? null : sysUser.getNickName();
    }



    /**
     * 查询门店下的用户信息
     *
     * @param storeId
     * @return
     */

    @Override
    public List<SysUserVo> queryById(Long storeId) {
        return  baseMapper.selectVoLists(storeId);
    }

    /**
     * 查询用户下的区域信息
     *
     * @param userId
     * @return
     */
    @Override
    public List<Long> selectUserAreaListByUser(Long userId) {
        List<SysAreaVo> sysAreaVos = baseMapper.selectUserAreaListByUser(userId);
        List<Long> areaIds = sysAreaVos.stream().map(SysAreaVo::getAreaId).collect(Collectors.toList());
        return areaIds;
    }


    /**
     * 查询当前登入用户的设备信息
     *
     * @param userId
     * @return
     */
    @Override
    public List<Long> selectUserDeviceListByUser(Long userId) {
        List<SysUserDevice> sysUserDevices = baseMapper.selectUserDeviceListByUser(Arrays.asList(userId));
        List<Long> deviceIds = sysUserDevices.stream()
                .map(SysUserDevice::getDeviceId)
                .collect(Collectors.toList());
        return deviceIds;
    }

    /**
     * 获取管理员id
     * @return
     */
    @Override
    public Long getUserAdminId() {
        return baseMapper.getUserAdminId();
    }


    /**
     * 获取当前用户下的门店信息
     *
     * @param userId
     * @return
     */
    @Override
    public List<SysStoreVo> selectUserStoresListByUser(Long userId) {
        SysStoreBo sysStoreBo = new SysStoreBo();
        sysStoreBo.setUserId(userId);
        return baseMapper.selectUserStoresListByUser(sysStoreBo);
    }

    @Override
    public List<Long> selectUserIdsLikeNickName(String userName) {
        List<SysUser> sysUsers = baseMapper.selectList(new LambdaQueryWrapper<SysUser>()
            .like(SysUser::getNickName, userName));
        return sysUsers.stream()
            .map(SysUser::getUserId)
            .filter(Objects::nonNull)
            .collect(Collectors.toList());
    }
}
